package com.dingpeikeji.quickdeer.core.modules.sys.web;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.config.Global;
import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.utils.StringUtils;
import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.SysAds;
import com.dingpeikeji.quickdeer.core.modules.sys.service.SysAdsService;

/**
 * 广告管理Controller
 * @author lh
 * @version 2016-11-11
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/ads")
public class SysAdsController extends BaseController {

	@Autowired
	private SysAdsService sysAdsService;
	
	@ModelAttribute
	public SysAds get(@RequestParam(required=false) String id) {
		SysAds entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = sysAdsService.get(id);
		}
		if (entity == null){
			entity = new SysAds();
		}
		return entity;
	}
	
	@RequiresPermissions("ads:sysAds:view")
	@RequestMapping(value = {"list", ""})
	public String list(SysAds sysAds, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<SysAds> page = sysAdsService.findPage(new Page<SysAds>(request, response), sysAds); 
		model.addAttribute("page", page);
		return "modules/sys/sysAdsList";
	}

	@RequiresPermissions("ads:sysAds:view")
	@RequestMapping(value = "form")
	public String form(SysAds sysAds, Model model) {
		model.addAttribute("sysAds", sysAds);
		return "modules/sys/sysAdsForm";
	}

	@RequiresPermissions("ads:sysAds:edit")
	@RequestMapping(value = "save")
	public String save(SysAds sysAds, Model model, RedirectAttributes redirectAttributes) throws IllegalStateException, IOException {
		if (!beanValidator(model, sysAds)){
			return form(sysAds, model);
		}
		sysAdsService.save(sysAds);
		addMessage(redirectAttributes, "保存广告信息成功");
		return "redirect:"+Global.getAdminPath()+"/sys/ads/?repage";
	}
	
	@RequiresPermissions("ads:sysAds:edit")
	@RequestMapping(value = "delete")
	public String delete(SysAds sysAds, RedirectAttributes redirectAttributes) {
		sysAdsService.delete(sysAds);
		addMessage(redirectAttributes, "删除广告信息成功");
		return "redirect:"+Global.getAdminPath()+"/sys/ads/?repage";
	}

}